﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;

namespace PortalCurriculo.Domain.Helpers
{
    public static class MailHelper
    {
        public static void EnviarEmail(string assunto, string mensagem, Email email, List<Pessoa> destinatarios)
        {
            var fromAddress = new MailAddress(email.ContaEmail.Email, email.DisplayName ?? email.ContaEmail.DisplayName);
            var mailMessage = new MailMessage
            { 
                From = fromAddress,
                Priority = MailPriority.Normal,
                IsBodyHtml = true,
                Subject = assunto,
                Body = mensagem,
                SubjectEncoding = Encoding.GetEncoding("ISO-8859-1"),
                BodyEncoding = Encoding.GetEncoding("ISO-8859-1")
            };

            if (destinatarios.Count == 1)
                mailMessage.To.Add(destinatarios.First().Email);
            else
            {
                foreach (var pessoa in destinatarios)
                {
                    mailMessage.To.Add(fromAddress);
                    mailMessage.Bcc.Add(pessoa.Email);
                }
            }

            var smtpClient = new SmtpClient
                              {
                                  Credentials = new NetworkCredential(email.ContaEmail.Email, Util.Descriptografar(email.ContaEmail.Senha)),
                                  EnableSsl = true,
                                  Host = email.ContaEmail.SmtpHost,
                                  Port = email.ContaEmail.SmtpPort
                              };

            try
            {
                smtpClient.Send(mailMessage);
            }
            catch{}

            mailMessage.Dispose();
        }
    }
}
